#include "stdafx.h"
#include "cfixedframerate.h"


CFixedFrameRate::CFixedFrameRate(int framerate)
{
	m_framerate = framerate;
	QueryPerformanceCounter((LARGE_INTEGER*)&m_t0);
}


CFixedFrameRate::~CFixedFrameRate()
{
}

double CFixedFrameRate::getFrameRate()
{
	return 1.0/(double)m_framerate;
}

void CFixedFrameRate::endFrame()
{
	__int64 t1,diff,actualizacionesPorSegundo;
	double counter_duration, my_frame_duration,elapsed_time, sleepTime;

	//llamada al contador 
	QueryPerformanceCounter((LARGE_INTEGER*)&t1);

	//hallar la diferencia
	diff = t1-m_t0;
	
	//pedir la frecuencia del contador
	QueryPerformanceFrequency((LARGE_INTEGER*)&actualizacionesPorSegundo);
	counter_duration = (1.0/(double)actualizacionesPorSegundo);
	
	elapsed_time = ((double)(diff*counter_duration))*1000;

	my_frame_duration = getFrameRate()*1000;
	sleepTime = my_frame_duration - elapsed_time;

	if(sleepTime < 0) sleepTime = 0;
	
	Sleep((DWORD)sleepTime);
	

	//sleep hasta el final del tiempo de frame deseado
	QueryPerformanceCounter((LARGE_INTEGER*)&m_t0);
}